package TCPThread.file;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class MyRunable implements Runnable{


    Socket socket = new Socket();

    public MyRunable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            String s = UUID.randomUUID().toString().replace("-","");


            BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
            BufferedOutputStream bufferedOutputStream  = new BufferedOutputStream(new FileOutputStream("picture/"+s+".png"));
            int x;
            byte[] bytes = new byte[1024];
            while ((x=bufferedInputStream.read(bytes))!=-1){
                bufferedOutputStream.write(bytes,0,x);
            }

            BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream()));
            bufferedWriter.write("传输成功");

            bufferedWriter.newLine();
            bufferedWriter.flush();


        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}
